package cn.njupt.cmpSort;

import java.text.DecimalFormat;

public  abstract class Sort<E extends Comparable<E>> implements Comparable<Sort<E>>{

    protected E[] array;

    //比较次数
    private int cmpCount;

    //交换次数
    private int swapCount;

    private long time;

    private DecimalFormat fmt = new DecimalFormat("#.00");

    public void sort(E[] array){
        if(array==null || array.length<2)return;
        this.array=array;

        long begin=System.currentTimeMillis();
        sort();
        time=System.currentTimeMillis()-begin;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(Sort<E> o) {
        return (int)(this.time-o.time);
    }

    public abstract void sort();

    /**
     *
     * @param i
     * @param j
     * @return 0,代表array[i]==array[j]
     *         >0,代表array[i]>array[j]
     *        <0,代表array[i]<array[j]
     */
    public int cmp(int i,int j){
        cmpCount++;
        return array[i].compareTo(array[j]);
    }

    public int cmpElements(E v1,E v2){
        cmpCount++;
        return v1.compareTo(v2);
    }

    public void swap(int i,int j){
        swapCount++;
        E temp=array[i];
        array[i]=array[j];
        array[j]=temp;
    }

    private String numberString(int number) {
        if (number < 10000) return "" + number;

        if (number < 100000000) return fmt.format(number / 10000.0) + "万";
        return fmt.format(number / 100000000.0) + "亿";
    }

    @Override
    public String toString() {
        String timeStr = "耗时：" + (time / 1000.0) + "s(" + time + "ms)";
        String compareCountStr = "比较：" + numberString(cmpCount);
        String swapCountStr = "交换：" + numberString(swapCount);
        return "【" + getClass().getSimpleName() + "】\n"
                + timeStr + " \t"
                + compareCountStr + "\t "
                + swapCountStr + "\n"
                + "------------------------------------------------------------------";

    }





}
